package com.math.aistudykbr.config;

import com.math.aistudykbr.interceptor.RequestLoggingInterceptor;
import com.math.aistudykbr.interceptor.UserInfoInterceptor;
import com.math.aistudykbr.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.concurrent.TimeUnit;

@Configuration
@RequiredArgsConstructor
@Slf4j
public class MVCConfig implements WebMvcConfigurer {

    private final JwtUtil jwtUtil;

    @Value("${file.server.host}")
    private String serverHost;

    /**
     * 添加拦截器配置
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        log.info("--------------------进入WebConfig--------------------");
        registry.addInterceptor(new UserInfoInterceptor(jwtUtil))
                .excludePathPatterns("/api/user/**", "**", "/files/**");

        // 添加请求日志拦截器
        registry.addInterceptor(new RequestLoggingInterceptor())
                .addPathPatterns("/**");
    }

    /**
     * 后端全局跨域配置
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:5173", "http://localhost:4000") // 指定前端地址
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 关键点：添加OPTIONS
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600); // 预检请求缓存时间（秒）
    }

    /**
     * 资源处理器配置
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/files/**")
                .addResourceLocations("file:./resource-xmind/")
                .setCacheControl(CacheControl.maxAge(365, TimeUnit.DAYS));
    }

    @Bean
    public String fileServerUrl() {
        return serverHost + "/files/";
    }
}
